"""
简化版智能客服平台
包含登录、个人中心和基本客服对话功能
"""

import streamlit as st
import json
import hashlib
import uuid
from datetime import datetime
from pathlib import Path

# 页面配置
st.set_page_config(
    page_title="智能客服平台",
    page_icon="🤖",
    layout="wide",
    initial_sidebar_state="collapsed"
)

# CSS样式
st.markdown("""
<style>
    .main .block-container {
        padding-top: 1rem;
        padding-bottom: 1rem;
    }
    
    .user-info {
        background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 1rem;
        border-radius: 10px;
        margin-bottom: 1rem;
    }
    
    .order-card {
        background: #f8f9fa;
        border-radius: 8px;
        padding: 1rem;
        margin: 0.5rem 0;
        border-left: 4px solid #007bff;
    }
    
    .chat-container {
        background: white;
        border-radius: 10px;
        padding: 1rem;
        margin: 1rem 0;
    }
</style>
""", unsafe_allow_html=True)

# ===============================
# 数据管理类
# ===============================

class SimpleUserManager:
    """简化的用户管理器"""
    
    def __init__(self):
        self.users_file = Path("simple_users.json")
        self.orders_file = Path("simple_orders.json")
        self.load_data()
    
    def load_data(self):
        """加载数据"""
        # 加载用户数据
        if self.users_file.exists():
            with open(self.users_file, 'r', encoding='utf-8') as f:
                self.users = json.load(f)
        else:
            self.users = {
                "demo@test.com": {
                    "username": "演示用户",
                    "password": hashlib.sha256("123456".encode()).hexdigest(),
                    "created_at": "2024-01-01"
                }
            }
            self.save_users()
        
        # 加载订单数据
        if self.orders_file.exists():
            with open(self.orders_file, 'r', encoding='utf-8') as f:
                self.orders = json.load(f)
        else:
            self.orders = {
                "demo@test.com": [
                    {
                        "order_id": "2024070300001",
                        "status": "已发货",
                        "total_amount": 299.00,
                        "items": ["智能手机保护壳"],
                        "created_at": "2024-07-03"
                    },
                    {
                        "order_id": "2024070200001", 
                        "status": "已送达",
                        "total_amount": 1299.00,
                        "items": ["无线蓝牙耳机"],
                        "created_at": "2024-07-02"
                    }
                ]
            }
            self.save_orders()
    
    def save_users(self):
        """保存用户数据"""
        with open(self.users_file, 'w', encoding='utf-8') as f:
            json.dump(self.users, f, ensure_ascii=False, indent=2)
    
    def save_orders(self):
        """保存订单数据"""
        with open(self.orders_file, 'w', encoding='utf-8') as f:
            json.dump(self.orders, f, ensure_ascii=False, indent=2)
    
    def login(self, email, password):
        """用户登录"""
        if email in self.users:
            stored_password = self.users[email]["password"]
            input_password = hashlib.sha256(password.encode()).hexdigest()
            if stored_password == input_password:
                return True, self.users[email]
        return False, None
    
    def register(self, email, username, password):
        """用户注册"""
        if email in self.users:
            return False, "邮箱已存在"
        
        self.users[email] = {
            "username": username,
            "password": hashlib.sha256(password.encode()).hexdigest(),
            "created_at": datetime.now().strftime("%Y-%m-%d")
        }
        
        # 为新用户创建空订单列表
        self.orders[email] = []
        
        self.save_users()
        self.save_orders()
        return True, "注册成功"
    
    def get_user_orders(self, email):
        """获取用户订单"""
        return self.orders.get(email, [])

# 全局用户管理器
@st.cache_resource
def get_user_manager():
    return SimpleUserManager()

# ===============================
# 客服功能类
# ===============================

class SimpleCustomerService:
    """简化的客服系统"""
    
    def __init__(self):
        self.knowledge_base = {
            "退货": "我们支持7天无理由退货，商品需保持原包装完好。",
            "配送": "全国包邮，1-3个工作日内送达。",
            "支付": "支持微信支付、支付宝、银行卡等多种支付方式。",
            "客服": "客服工作时间：9:00-21:00，节假日正常服务。",
            "会员": "会员享有积分返还、专属优惠、优先客服等权益。"
        }
    
    def get_response(self, user_input, user_email=None):
        """获取客服回复"""
        user_input_lower = user_input.lower()
        
        # 订单查询
        if "订单" in user_input or "order" in user_input_lower:
            return self.handle_order_query(user_input, user_email)
        
        # 知识库查询
        for keyword, response in self.knowledge_base.items():
            if keyword in user_input:
                return f"📋 **{keyword}相关政策**\n\n{response}\n\n如需更多帮助，请联系人工客服。"
        
        # 默认回复
        return f"感谢您的咨询！您的问题是：{user_input}\n\n我会尽快为您处理。如需人工服务，请拨打客服电话：400-123-4567"
    
    def handle_order_query(self, user_input, user_email):
        """处理订单查询"""
        if not user_email:
            return "请先登录后查询订单信息。"
        
        user_manager = get_user_manager()
        orders = user_manager.get_user_orders(user_email)
        
        if not orders:
            return "您暂时没有订单记录。"
        
        # 提取订单号
        import re
        order_pattern = r'\d{10,15}'
        order_matches = re.findall(order_pattern, user_input)
        
        if order_matches:
            order_id = order_matches[0]
            for order in orders:
                if order["order_id"] == order_id:
                    return f"""📦 **订单查询结果**

🆔 订单号：{order['order_id']}
📋 状态：{order['status']}
💰 金额：¥{order['total_amount']}
🛍️ 商品：{', '.join(order['items'])}
📅 下单时间：{order['created_at']}

如有疑问，请联系客服。"""
            
            return f"未找到订单号 {order_id}，请检查订单号是否正确。"
        else:
            # 显示最近订单
            recent_order = orders[-1]
            return f"""📦 **您的最近订单**

🆔 订单号：{recent_order['order_id']}
📋 状态：{recent_order['status']}
💰 金额：¥{recent_order['total_amount']}
🛍️ 商品：{', '.join(recent_order['items'])}

要查询具体订单，请提供完整订单号。"""

# 全局客服系统
@st.cache_resource
def get_customer_service():
    return SimpleCustomerService()

# ===============================
# 页面函数
# ===============================

def init_session_state():
    """初始化会话状态"""
    if "logged_in" not in st.session_state:
        st.session_state.logged_in = False
    if "user_email" not in st.session_state:
        st.session_state.user_email = None
    if "user_info" not in st.session_state:
        st.session_state.user_info = None
    if "chat_messages" not in st.session_state:
        st.session_state.chat_messages = []
    if "show_user_center" not in st.session_state:
        st.session_state.show_user_center = False

def render_login_page():
    """渲染登录页面"""
    st.title("🤖 智能客服平台")
    
    # 登录/注册选项卡
    login_tab, register_tab = st.tabs(["🔐 登录", "📝 注册"])
    
    with login_tab:
        with st.form("login_form"):
            st.subheader("用户登录")
            email = st.text_input("邮箱")
            password = st.text_input("密码", type="password")
            
            col1, col2 = st.columns(2)
            with col1:
                login_btn = st.form_submit_button("登录", type="primary", use_container_width=True)
            with col2:
                demo_btn = st.form_submit_button("演示登录", use_container_width=True)
            
            if login_btn and email and password:
                user_manager = get_user_manager()
                success, user_info = user_manager.login(email, password)
                
                if success:
                    st.session_state.logged_in = True
                    st.session_state.user_email = email
                    st.session_state.user_info = user_info
                    st.success("登录成功！")
                    st.rerun()
                else:
                    st.error("邮箱或密码错误")
            
            if demo_btn:
                st.session_state.logged_in = True
                st.session_state.user_email = "demo@test.com"
                st.session_state.user_info = {
                    "username": "演示用户",
                    "created_at": "2024-01-01"
                }
                st.success("演示登录成功！")
                st.rerun()
    
    with register_tab:
        with st.form("register_form"):
            st.subheader("用户注册")
            reg_email = st.text_input("邮箱地址")
            reg_username = st.text_input("用户名")
            reg_password = st.text_input("密码", type="password")
            reg_password_confirm = st.text_input("确认密码", type="password")
            
            register_btn = st.form_submit_button("注册", type="primary", use_container_width=True)
            
            if register_btn:
                if not all([reg_email, reg_username, reg_password, reg_password_confirm]):
                    st.error("请填写完整信息")
                elif reg_password != reg_password_confirm:
                    st.error("两次输入的密码不一致")
                elif len(reg_password) < 6:
                    st.error("密码长度至少6位")
                else:
                    user_manager = get_user_manager()
                    success, message = user_manager.register(reg_email, reg_username, reg_password)
                    
                    if success:
                        st.success(message)
                    else:
                        st.error(message)
    
    # 提示信息
    st.info("💡 演示账号：demo@test.com，密码：123456")

def render_header():
    """渲染页面头部"""
    col1, col2, col3 = st.columns([3, 1, 1])
    
    with col1:
        st.title("🤖 智能客服平台")
    
    with col2:
        if st.button("👤 个人中心", use_container_width=True):
            st.session_state.show_user_center = not st.session_state.show_user_center
    
    with col3:
        if st.button("🚪 退出登录", use_container_width=True):
            st.session_state.logged_in = False
            st.session_state.user_email = None
            st.session_state.user_info = None
            st.session_state.chat_messages = []
            st.session_state.show_user_center = False
            st.rerun()

def render_user_center():
    """渲染个人中心"""
    st.markdown("### 👤 个人中心")
    
    # 用户信息
    user_info = st.session_state.user_info
    st.markdown(f"""
    <div class="user-info">
        <h4>👋 欢迎，{user_info['username']}</h4>
        <p>📧 邮箱：{st.session_state.user_email}</p>
        <p>📅 注册时间：{user_info['created_at']}</p>
    </div>
    """, unsafe_allow_html=True)
    
    # 订单信息
    st.subheader("📦 我的订单")
    
    user_manager = get_user_manager()
    orders = user_manager.get_user_orders(st.session_state.user_email)
    
    if orders:
        for order in orders:
            st.markdown(f"""
            <div class="order-card">
                <h5>📦 订单 {order['order_id']}</h5>
                <p><strong>状态：</strong>{order['status']}</p>
                <p><strong>金额：</strong>¥{order['total_amount']}</p>
                <p><strong>商品：</strong>{', '.join(order['items'])}</p>
                <p><strong>下单时间：</strong>{order['created_at']}</p>
            </div>
            """, unsafe_allow_html=True)
    else:
        st.info("暂无订单记录")
    
    # 统计信息
    st.subheader("📊 账户统计")
    
    col1, col2, col3 = st.columns(3)
    with col1:
        st.metric("总订单数", len(orders))
    with col2:
        total_amount = sum(order['total_amount'] for order in orders)
        st.metric("总消费金额", f"¥{total_amount:.2f}")
    with col3:
        completed_orders = len([o for o in orders if o['status'] == '已送达'])
        st.metric("完成订单", completed_orders)
    
    if st.button("🔙 返回对话", type="primary"):
        st.session_state.show_user_center = False
        st.rerun()

def render_chat_interface():
    """渲染聊天界面"""
    st.subheader("💬 智能客服对话")
    
    # 显示用户信息
    user_info = st.session_state.user_info
    st.info(f"👋 您好，{user_info['username']}！有什么可以帮助您的吗？")
    
    # 显示聊天历史
    for message in st.session_state.chat_messages:
        with st.chat_message(message["role"]):
            st.write(message["content"])
    
    # 聊天输入
    user_input = st.chat_input("请输入您的问题...")
    
    if user_input:
        # 添加用户消息
        st.session_state.chat_messages.append({
            "role": "user",
            "content": user_input
        })
        
        # 显示用户消息
        with st.chat_message("user"):
            st.write(user_input)
        
        # 获取客服回复
        customer_service = get_customer_service()
        response = customer_service.get_response(user_input, st.session_state.user_email)
        
        # 添加助手消息
        st.session_state.chat_messages.append({
            "role": "assistant", 
            "content": response
        })
        
        # 显示助手回复
        with st.chat_message("assistant"):
            st.write(response)
    
    # 快捷操作
    st.subheader("⚡ 快捷操作")
    
    col1, col2, col3 = st.columns(3)
    
    with col1:
        if st.button("📦 查询订单", use_container_width=True):
            quick_query = "我想查询我的订单状态"
            st.session_state.chat_messages.append({"role": "user", "content": quick_query})
            
            customer_service = get_customer_service()
            response = customer_service.get_response(quick_query, st.session_state.user_email)
            st.session_state.chat_messages.append({"role": "assistant", "content": response})
            st.rerun()
    
    with col2:
        if st.button("🔄 退货政策", use_container_width=True):
            quick_query = "请问退货政策是什么？"
            st.session_state.chat_messages.append({"role": "user", "content": quick_query})
            
            customer_service = get_customer_service()
            response = customer_service.get_response(quick_query, st.session_state.user_email)
            st.session_state.chat_messages.append({"role": "assistant", "content": response})
            st.rerun()
    
    with col3:
        if st.button("🚚 配送信息", use_container_width=True):
            quick_query = "请问配送需要多久？"
            st.session_state.chat_messages.append({"role": "user", "content": quick_query})
            
            customer_service = get_customer_service()
            response = customer_service.get_response(quick_query, st.session_state.user_email)
            st.session_state.chat_messages.append({"role": "assistant", "content": response})
            st.rerun()
    
    # 清空对话
    if st.button("🗑️ 清空对话"):
        st.session_state.chat_messages = []
        st.rerun()

def main():
    """主函数"""
    init_session_state()
    
    if not st.session_state.logged_in:
        render_login_page()
    else:
        render_header()
        
        if st.session_state.show_user_center:
            render_user_center()
        else:
            render_chat_interface()

if __name__ == "__main__":
    main()
